package com.fqy.thread.nosafe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * User: fqy
 * Date: 2021/8/31
 * Time: 17:14
 * Describe: ArrayList线程不安全问题
 */
public class NoSafeDemo {

    public static void main(String[] args) throws InterruptedException {

//        并发修改异常：java.util.ConcurrentModificationException
//        List<String> list = new ArrayList<>();
//        解决方法: 执行add()时候加个锁
//        解决方式1：
//        List<String> list = new Vector<>();
//        解决方式2：
        List<String> list = new CopyOnWriteArrayList<>();
        //解决方式3：Collections工具类
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0, 6));
//                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(list);
            },String.valueOf(i)).start();
        }

    }
    public static void setNotSafe()
    {
        Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet(new HashSet<>());//new HashSet<>();

        for (int i = 1; i <=30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }
    public static void mapNotSafe(){
        Map<String, String> map =  new ConcurrentHashMap<>();//new HashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,6));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

}
